package com.zking.filter;

import com.zking.config.config;
import com.zking.util.RedirectMsg;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/*
过滤器，检测登录状态
 */
public class AuthFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        if(config.is_debug){
            chain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        HttpSession session = httpRequest.getSession(false);

        boolean loggedIn = session != null && session.getAttribute("user")!=null;

        if(loggedIn){
            chain.doFilter(request, response);
        }else{
            httpRequest.setAttribute("msg", RedirectMsg.notLogin);
            httpRequest.setAttribute("pageName", RedirectMsg.loginPageName);
            httpRequest.setAttribute("url", RedirectMsg.loginUrl);
            httpRequest.getRequestDispatcher("redirect.jsp").forward(request, response);
        }

    }
}
